package net.wanho.listener;

import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.java.Log;
import net.wanho.po.Student;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * Author：汤小洋
 * Date：2024-09-05 14:14
 * Description：<描述>
 */
@Component
public class MsgLIstener {

    @RabbitListener(queues = "${shop.queue}")
    // public void readMsg(String msg){
    public void readMsg(Student stu){
        System.out.println("--------------" + stu);
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "queue2"),
            exchange = @Exchange(value = "exchange2.fanout", type = ExchangeTypes.FANOUT)
    ))
    public void readMsg2(String msg){
        System.out.println("=====================" + msg);
    }

    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "queue3"),
            exchange = @Exchange(value = "exchange3.direct", type = ExchangeTypes.DIRECT),
            key = "key3"
    ))
    public void readMsg3(String msg, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag){
        System.out.println("=====================" + msg);

        // todo 业务处理

        // 确认消息，处理消息功能
        // channel.basicAck(tag, false); // 参数1：消息的tag，参数2：是否批量确认

        // 未确认消息，处理消息失败
        // channel.basicNack(tag, false, false); // 参数1：消息的tag，参数2：是否批量确认，参数3：是否重新放回队列

        // 未确认消息，拒绝消息
        channel.basicReject(tag, false); // 参数1：消息的tag，参数2：是否重新放回队列

        /**
         * 注意：如果未确认消息或拒绝消息，且不重新放入队列，那么消息会被丢弃，变成死信！
         */

    }

    @RabbitListener(queues = "normal.queue")
    public void paramMessage(String msg,Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag) throws IOException {
        // System.out.println("正常：" +  msg);
        // channel.basicAck(tag,false);

        // 模拟：如果是偶数，则业务处理正常，确认消息
        if(Integer.parseInt(msg.substring(2))%2 == 0){
            System.out.println("正常：" +  msg);
            channel.basicAck(tag,false);
        }else{
            // 如果是奇数，则业务处理失败，拒收消息，且不再重新放入队列
            channel.basicNack(tag,false,false);
        }
    }

    @RabbitListener(queues = "dead.queue")
    public void deathMessage(String msg,Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag) throws IOException {
        System.out.println("死信-----：" +  msg);
        channel.basicAck(tag,false);
    }

}
